<?php

namespace WebmanGrpc;

use support\Bootstrap;
use Webman\Config;
use WebmanGrpc\HttpGateway;
use WebmanGrpc\GrpcManager;

/**
 * Webman插件主类
 * 
 * 提供Webman框架的gRPC支持
 */
class Plugin implements Bootstrap
{
    /**
     * 启动插件
     * 
     * @param \Workerman\Worker $worker Worker实例
     * @return void
     */
    public static function start($worker)
    {
        // 获取配置
        $config = Config::get('plugin.endcms.webman-grpc', []);
        
        // 检查是否启用
        if (!($config['enable'] ?? true)) {
            return;
        }
        
        // 初始化gRPC扩展包
        $manager = GrpcManager::getInstance();
        $manager->initialize($config['grpc'] ?? []);
        
        // 注册服务
        self::registerServices($config['grpc']['services'] ?? []);
        
        // 添加拦截器
        self::addInterceptors($config['grpc']['interceptors'] ?? []);
        
        // 预热连接
        if (!empty($config['grpc']['warm_up']['addresses'])) {
            $manager->warmUpConnections(
                $config['grpc']['warm_up']['addresses'], 
                $config['grpc']['warm_up']['options'] ?? []
            );
        }
        
        // 预热序列化
        if (!empty($config['grpc']['warm_up']['message_classes'])) {
            $manager->warmUpSerialization($config['grpc']['warm_up']['message_classes']);
        }
        
        // 初始化HTTP网关
        if ($config['http_gateway']['enabled'] ?? false) {
            new HttpGateway($config['http_gateway']);
        }
    }
    
    /**
     * 注册服务
     * 
     * @param array $services 服务列表
     * @return void
     */
    protected static function registerServices(array $services): void
    {
        foreach ($services as $serviceName => $serviceConfig) {
            $className = $serviceConfig['class'] ?? null;
            $options = $serviceConfig['options'] ?? [];
            
            if ($className) {
                Grpc::registerService($serviceName, $className, $options);
            }
        }
    }
    
    /**
     * 添加拦截器
     * 
     * @param array $interceptors 拦截器列表
     * @return void
     */
    protected static function addInterceptors(array $interceptors): void
    {
        foreach ($interceptors as $interceptorConfig) {
            $className = $interceptorConfig['class'] ?? null;
            $priority = $interceptorConfig['priority'] ?? 100;
            
            if ($className) {
                Grpc::addInterceptor($className, $priority);
            }
        }
    }
}